package com.ruoyi.web.controller.zbg;

import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.ruoyi.common.utils.TokenUtils;
import com.ruoyi.system.domain.vo.zbg.User;
import com.ruoyi.system.domain.zbg.LoginRequest;
import com.ruoyi.system.domain.zbg.LoginResponse;
import com.ruoyi.system.service.UserService;
import com.ruoyi.system.service.impl.TokenServiceTest;
import com.ruoyi.web.tool.Result;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/login")
@Api(tags = "登录模块")
@Slf4j
public class Login {
    @Autowired
    private UserService userService;

    @Autowired
    private TokenServiceTest tokenServiceTest;
   @ApiOperation(value = "登录", notes = "登录接口")

    @PostMapping("/login")
    public ResponseEntity<?> login(@RequestBody LoginRequest loginRequest) throws Exception {
        log.info("登入请求: {}", loginRequest);
        String username = loginRequest.getUsername();
        String password = loginRequest.getPassword();
        User user = userService.validateUser(username, password);
        if (ObjectUtils.isEmpty(user)) {
            return ResponseEntity.badRequest().body("账号输入错误");
        }

//        String userData = String.format("{\"username\":\"%s\", \"roles\": [\"user\", \"admin\"]}", username);
        //将用户信息转换为json字符串，存入token中
        ObjectMapper objectMapper = new ObjectMapper();
        String userData = objectMapper.writeValueAsString(user);

        String token = tokenServiceTest.generateToken(userData);

        return ResponseEntity.ok(new LoginResponse(token));
    }
    @Autowired
    private TokenUtils tokenUtils;
@ApiOperation(value = "获取用户信息", notes = "获取用户信息接口")
    @GetMapping("/userinfo")
    public Result getUserInfo(@RequestHeader("Authorization") String authorization) throws Exception {
        log.info("获取用户信息请求: {}", authorization);
    if (authorization != null && authorization.startsWith("Bearer ")) {
            String token = authorization.substring(7);
            String userDataJson = tokenUtils.getUserDataFromToken(token);
            //将json数据转换为User对象
            if (userDataJson != null) {
                ObjectMapper mapper = new ObjectMapper();
                User user = mapper.readValue(userDataJson, User.class);
                return Result.success(user);
            } else {
                return Result.failed("token校验失败");
            }
        } else {
            return Result.failed("token为空");
        }
    }

}
